package com.mk.episodecalendar;

import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class EpisodeRepository {
	
	private String FEED_URL_FORMAT = "http://episodecalendar.com/android/rss_feed/%s/%s";
	private String SEEN_URL_FORMAT = "http://episodecalendar.com/android/check_off/%s/%s/%s/%s";
	
	public ArrayList<EpisodeCollection> GetEpisodes(User user)
	{
		ArrayList<EpisodeCollection> episodes = new ArrayList<EpisodeCollection>();
		
		URLConnection urlCon = null;
		try
		{
			URL url = new URL(String.format(FEED_URL_FORMAT, user.getUserName(), Global.ApplicationPrecferences.getAuthKey()));
			urlCon = url.openConnection();
		}
		catch (Exception e)
		{
			return episodes;
		}
		
		try
		{
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = db.parse(urlCon.getInputStream());
			doc.getDocumentElement().normalize();
			
			NodeList dateNodes = doc.getElementsByTagName("date");
			
			
			for(int i = 0; i < dateNodes.getLength(); i++)
			{
				episodes.add( HandleDateNode(dateNodes.item(i)) );
			}
		}
		catch (Exception e) 
		{
			return episodes;
		}
		
		return episodes;
	}
	
	private EpisodeCollection HandleDateNode(Node node)
	{
		String dateString = node.getAttributes().item(0).getNodeValue();
		ArrayList<Episode> episodes = new ArrayList<Episode>();
		
		NodeList episodeNodes = node.getChildNodes();
		for(int i = 0; i < episodeNodes.getLength(); i++)
		{
			Episode episode = HandleEpisodeNode(episodeNodes.item(i));
			if(episode != null)
				episodes.add(episode);
		}
		
		Date airDate = null;
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    try {
	    	airDate = (Date)formatter.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return new EpisodeCollection(airDate, episodes);		
	}
	
	private Episode HandleEpisodeNode(Node node)
	{
		if( node.getNodeType() == Node.ELEMENT_NODE)
		{
			String episodeId = "", show = "", number = "", name = "", summary = "";
			Boolean seen = false;
			NodeList episodeNodeElements = node.getChildNodes();
			for(int i = 0; i < episodeNodeElements.getLength(); i++)
			{
				Node n = episodeNodeElements.item(i);
				if(n.getNodeType() == Node.ELEMENT_NODE)
				{
					Node valueNode = n.getChildNodes().item(0);
					if(n.getNodeName().equals("id"))
					{
						episodeId = valueNode.getNodeValue();
					}
					if(n.getNodeName().equals("show"))
					{
						show = valueNode.getNodeValue();
					}
					else if(n.getNodeName().equals("number"))
					{
						number = valueNode.getNodeValue();
					}
					else if(n.getNodeName().equals("name"))
					{
						name = StringEscapeUtils.unescapeHtml(valueNode.getNodeValue());	
					}
					else if(n.getNodeName().equals("summary"))
					{
						summary = valueNode.getNodeValue().startsWith("No synopsis available.") ? "No synopsis available." : StringEscapeUtils.unescapeHtml(valueNode.getNodeValue());	
					}
					
					else if(n.getNodeName().equals("checked"))
					{
						seen = valueNode.getNodeValue().equals("true");
					}
				}
			}
			Episode episode = new Episode(episodeId, show, number, name, summary, seen);
			return episode;
		}
		
		return null;
	}
	
	public Boolean SetSeen(User user, String episodeId, Boolean seen)
	{
		URLConnection urlCon = null;
		try
		{
			URL url = new URL(String.format(SEEN_URL_FORMAT, episodeId, seen ? "1" : "0", user.getUserName(), Global.ApplicationPrecferences.getAuthKey()));
			urlCon = url.openConnection();
		}
		catch (Exception e)
		{
			return false;
		}
		
		try
		{
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = db.parse(urlCon.getInputStream());
			String result = doc.getElementsByTagName("result").item(0).getFirstChild().getNodeValue();
			
			return result.equals("true") ? seen : false;
		}
		catch (Exception e) 
		{
			return false;
		}
	}
}
